<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-if="type == 3"
        v-model="forms.air_code_show_name"
        :label-width="0"
        @click="checkAir"
        name="air_code_show_name"
        disabled
        :left-icon="icon.airIcon"
        placeholder="选择航班号"
        autocomplete="off"
        :rules="[{ required: true, message: '请选择航班号' }]"
      />
      <van-field
        v-if="type == 2 || type == 3 || type == 4"
        v-model="forms.departure_time_show"
        :label-width="0"
        @click="checkFullTime"
        name="departure_time_show"
        :left-icon="icon.time"
        :placeholder="timeName"
        autocomplete="off"
        disabled
        :rules="[{ required: true, message: `请选择${timeName}` }]"
      />
      <van-field
        v-model="forms.from_address"
        :label-width="0"
        name="from_address"
        :placeholder="formName"
        @click="openPoi(1)"
        disabled
        class="fo-form"
        left-icon="location"
        autocomplete="off"
        :rules="[{ required: true, message: `请${formName}` }]"
      />
      <van-field
        v-model="forms.to_address"
        name="to_address"
        :label-width="0"
        :placeholder="toName"
        disabled
        @click="openPoi(2)"
        class="to-form"
        left-icon="location"
        autocomplete="off"
        :rules="[{ required: true, message: `请${toName}` }]"
      />
      <van-field name="is_because" label="用车类型：" label-width="2.67rem">
        <template #input>
          <van-radio-group
            @change="changePublicAndPrivateFlag"
            v-model="forms.is_because"
            direction="horizontal"
          >
            <van-radio name="1">因公</van-radio>
            <van-radio name="2">因私</van-radio>
          </van-radio-group>
        </template>
        <!--        <template #label>-->
        <!--          <span @click="checkCarType"-->
        <!--            >{{ forms.carType.label }} <img :src="downIcon"-->
        <!--          /></span>-->
        <!--        </template>-->
      </van-field>
      <van-field
        v-model="forms.passenger_name"
        label-width="2.67rem"
        name="passenger_name"
        @click="openMan"
        label="请选择用车人："
        disabled
        autocomplete="off"
        placeholder="选择出行人"
        :rules="[{ required: true, message: '选择出行人' }]"
      />
      <!--      <van-field-->
      <!--        v-if="-->
      <!--          forms.is_because == '1' &&-->
      <!--            $store.state.configureInfo.approval_type == '1'-->
      <!--        "-->
      <!--        v-model="forms.passenger_approver"-->
      <!--        label-width="2.67rem"-->
      <!--        name="passenger_approver"-->
      <!--        label="请选择审批单:"-->
      <!--        autocomplete="off"-->
      <!--        disabled-->
      <!--        placeholder="选择审批单"-->
      <!--        @click="openApprover"-->
      <!--        :rules="[{ required: true, message: '选择审批单' }]"-->
      <!--      />-->
    </van-cell-group>
    <div style="margin: 0.5rem;">
      <van-button
        round
        block
        color="notFinishedOrder ? #c1c1c1 : ''"
        type="primary"
        native-type="submit"
        :disabled="notFinishedOrder ? true : false"
      >
        查询
      </van-button>
    </div>
  </van-form>
  <!--  上拉控件-->
  <TopPull
    v-model:show="showCarType"
    :columns="ENUMS.CarType"
    v-if="showCarType"
    @change="changeCarType"
  ></TopPull>
  <FullTime
    v-model:show="showFullTime"
    :minDate="timesParam.minDate"
    :maxDate="timesParam.maxDate"
    :defaultTime="timesParam.defaultTime"
    v-if="showFullTime"
    @change="changeFullTime"
  >
  </FullTime>
  <router-view
    v-slot="{ Component }"
    @commitApprovalList="commitApprovalList"
    @commitTripPeople="commitTripPeople"
    @commitPoiAddress="changePoi"
  >
    <transition name="van-slide-right">
      <component :is="Component"></component>
    </transition>
  </router-view>
  <!-- poi选择 -->
  <SearchPoi
    v-model:show="showPoi"
    @change="changePoi"
    :title="poiType == '1' ? '选择出发地' : '选择目的地'"
  />
  <!--  搜索航班-->
  <SearchAir v-model:show="showAir" @change="changeAir"></SearchAir>
</template>

<script>
import { computed, getCurrentInstance, reactive, toRefs, watch } from "vue";
import TopPull from "/@/components/TopPull/TopPull.vue";
import FullTime from "/@/components/FullTime/FullTime.vue";
import SearchPoi from "/@/components/SearchPoi/SearchPoi.vue";
import SearchAir from "/@/components/SearchAir/SearchAir.vue";
import ENUMS from "../../../assets/enum/searchCar";
import { format, addDays, addMinutes } from "date-fns";
import { Toast } from "vant";
import {
  driving,
  drivingClear,
  nglatToAddress,
  addressInfo
} from "/@/assets/map/searchCarMap/getMapData.js";
const downIcon =
  "";
import airIcon from "/@/assets/img/air-icon.png";
import time from "/@/assets/img/time.png";
import { addressToDetail } from "../../../assets/map/searchCarMap/getMapData";

export default {
  name: "carAirport",
  components: { TopPull, FullTime, SearchPoi, SearchAir },
  props: {
    tab: Number,
    type: String, // 1: 立即用车， 2：预约用车
    notFinishedOrder: [null, String]
  },
  setup(props) {
    const { proxy } = getCurrentInstance();
    const entDays = 3, // 默认最小时间的多少天之后能用车
      min = 15; // 分钟之后
    const pageData = reactive({
      poiType: "", // 1: 出发， 2到达 // 用于确定打开的是出发还是到达poi
      icon: {
        airIcon: airIcon,
        time: time
      },
      forms: {
        air_code: "", // 航班号
        air_code_show_name: "", // 显示的航班信息
        flight_depcode: "", // 出发机场三字码
        flight_arrcode: "", // 到达机场三字码
        departure_time: "", // 用车时间
        departure_time_show: "", // 用车时间去掉秒
        flt_takeoff_time: "", // 航班时间（送机： 出发 / 接机：到达）
        passenger_name: "", // 用车人姓名
        from_address: "", // 出发地
        to_address: "", // 目的地
        from_address_ALL: {}, // 出发地所有数据
        to_address_ALL: {}, // 目的地所有的数据
        searchType: props.type, // 搜索的类型
        is_because: "1", // 因公因私
        approvers: {}, // 审批单
        mans: {}, // 出行人
        carType: {
          // 用车类型
          label: "不限车型",
          values: ""
        }
      },
      timesParam: {
        // 传入预约时间的最大时间和最小时间
        minDate: addMinutes(new Date(), min), // 多少分钟之后
        maxDate: addDays(new Date(), entDays), // 多少天之内
        defaultTime: addMinutes(new Date(), min) // 多少分钟之后
      },
      showPoi: false, // 打开poi
      showCarType: false, // 打开用车类型
      showFullTime: false, // 打开时间选择
      showAir: false, // 打开航班选择
      ENUMS, // 枚举
      downIcon // 图标
    });

    const comutedAll = {
      timeName: computed(() => {
        switch (props.type) {
          case "2":
            return "请选择用车时间";
            break;
          case "3":
            return "航班到达后用车时间";
            break;
          case "4":
            return "请选择用车时间";
            break;
        }
      }),
      formName: computed(() => {
        switch (props.type) {
          case "3":
            return "选择出发航站楼";
            break;
          default:
            return "选择出发地";
        }
      }),
      toName: computed(() => {
        switch (props.type) {
          case "4":
            return "选择目的地航站楼";
            break;
          default:
            return "选择目的地";
        }
      })
    };
    // 保存因公因私
    const changePublicAndPrivateFlag = () => {
      proxy.$store.commit(
        "SET_PUBLIC_ADN_PRIVATE_FLAG",
        pageData.forms.is_because === "1" ? "0" : "1"
      );
    };
    // 控件的回调
    const compCall = {
      // 获取审批单数据
      commitApprovalList(val) {
        pageData.forms.approvers = val;
        // compCall.getTravelStandardsNew();
      },
      // 获取差旅标准
      async getTravelStandardsNew() {
        const data = {
          type: 2,
          member_id: localStorage.getItem("memberId"),
          passenger_member_ids: state.passenger_member_ids,
          apply_detail_id: state.approval_list.apply_detail_id
        };
        const url = "/security/v1/common/getTravelStandardsNew";
        let res = await proxy.$axiosJson(url, data);
        if (res.biz_result === "SUCCESS" && res.ret_code === "10000") {
          state.approval_rule_list = res.data;
        }
      },
      // 获取出行人
      commitTripPeople(val) {
        let data = {};
        try {
          data = val && val.length ? val[0] || {} : {};
          pageData.forms.passenger_name = data.member_name || "";
        } catch (e) {
          data = {};
        }
        pageData.forms.mans = data;
      }
    };
    const pageMethod = {
      onSubmit() {
        // 提交
        console.log(pageData.forms);
        pageMethod.setSearchParam();
        proxy.$router.push({
          path: "/carInfo",
          query: {}
        });
      },
      checkCarType() {
        // 打开用车类型
        pageData.showCarType = true;
      },
      changeCarType(nowCarType) {
        // 用车类型回调
        pageData.forms.carType = nowCarType || {};
      },
      checkAir() {
        pageData.showAir = true;
      },
      changeAir(data) {
        // 设置最小时间
        const minDate = addMinutes(
          new Date((data.flight_arrtime_plan_date || "").replace(/-/g, "/")),
          min
        );
        // pageData.timesParam.minDate
        const minDate1 = addMinutes(new Date(), min);
        if (minDate >= minDate1) {
          pageData.timesParam.minDate = minDate;
          pageData.timesParam.defaultTime = minDate;
          pageData.timesParam.maxDate = addDays(minDate, entDays);
        } else {
          pageData.timesParam.minDate = minDate1;
          pageData.timesParam.defaultTime = minDate1;
          pageData.timesParam.maxDate = addDays(minDate1, entDays);
        }
        let flight_arrtime_plan_date = data.flight_arrtime_plan_date;
        try {
          flight_arrtime_plan_date = format(
            new Date((flight_arrtime_plan_date || "").replace(/-/g, "/")),
            "yyyy-MM-dd HH:mm"
          );
        } catch (e) {}
        // 航班号
        pageData.forms.air_code = data.flight_no || "";
        pageData.forms.air_code_show_name = data.flight_no
          ? data.flight_no +
            (flight_arrtime_plan_date
              ? ` (抵达时间：${flight_arrtime_plan_date})`
              : "")
          : "";
        // 出发机场三字码
        pageData.forms.flight_depcode = data.flight_depcode || "";
        // 到达机场三字码
        pageData.forms.flight_arrcode = data.flight_arrcode || "";
        // 上车时间
        pageData.forms.departure_time = "";
        pageData.forms.departure_time_show = "";
        // pageData.forms.departure_time = format(
        //   pageData.timesParam.minDate || "",
        //   "yyyy-MM-dd HH:mm"
        // );
        pageData.forms.flt_takeoff_time = data.flight_arrtime_plan_date || "";
        const setAddress = nowCitys => {
          pageData.forms.from_address_ALL = {
            address: nowCitys.address || "",
            code: nowCitys.cityCode || "",
            flat: nowCitys.flat || "",
            flng: nowCitys.flng || "",
            name: nowCitys.cityName || "",
            simple_address: nowCitys.cityName || ""
          };
          pageData.forms.from_address = nowCitys.address || "";
        };
        // const lngLat = (data.flight_arr_location || "").split(",");
        const from_address = data.flight_arr_airport
          ? data.flight_arr_airport + "机场"
          : "";
        // if (lngLat.length >= 2) {
        //   const lngLatObj = {
        //     lat: lngLat[1] || "",
        //     lng: lngLat[0] || ""
        //   };
        //   proxy.$store.commit("TOGGLE_LOADING", true);
        //   nglatToAddress(lngLatObj, nowCity => {
        //     proxy.$store.commit("TOGGLE_LOADING", false);
        //     const nowCitys = addressInfo(nowCity, lngLatObj);
        //     setAddress(nowCitys);
        //   });
        // } else
        if (from_address) {
          proxy.$store.commit("TOGGLE_LOADING", true);
          addressToDetail(from_address, nowDetail => {
            proxy.$store.commit("TOGGLE_LOADING", false);
            const nowCitys = addressInfo((nowDetail.geocodes || [])[0] || {});
            setAddress(nowCitys);
          });
        } else {
          Toast("航班信息错误");
        }
      },
      checkFullTime() {
        // 打开时间控件
        pageData.showFullTime = true;
      },
      changeFullTime(time) {
        // 时间回调
        pageData.forms.departure_time = format(time, "yyyy-MM-dd HH:mm:ss");
        pageData.forms.departure_time_show = format(time, "yyyy-MM-dd HH:mm");
      },
      openApprover() {
        // 打开审批人列表
        proxy.$router.push({
          path: "/home/approvalList",
          query: {}
        });
      },
      openMan() {
        // 打开出行人选择
        if (JSON.stringify(pageData.forms.approvers) !== "{}") {
          Toast("您已选择审批单，不可以修改出行人");
          return false;
        }
        proxy.$router.push({
          path: "/home/tripPeople"
        });
      },
      openPoi(poiType) {
        // 1: 出发， 2到达
        // 打开poi选择弹窗
        pageData.showPoi = true;
        pageData.poiType = poiType;
      },
      changePoi(data) {
        let fromKey = "from_address";
        pageData.showPoi = false;
        if (pageData.poiType == 2) fromKey = "to_address";
        pageData.forms[fromKey + "_ALL"] = JSON.parse(JSON.stringify(data));
        pageData.forms[fromKey] = data.name + " " + data.address;
        pageMethod.drivingMap();
      },
      drivingMap() {
        // 地图绘制
        const from = pageData.forms.from_address_ALL,
          to = pageData.forms.to_address_ALL;
        if (from.flng && from.flat && to.flng && to.flat)
          driving(from, to, true);
        else drivingClear();
      },
      setSearchParam() {
        // 将搜索的数据进行页面缓存
        proxy.$store.commit("SET_SEARCH_PARAM", pageData.forms);
      }
    };

    watch(
      () => props.tab,
      item => {
        if (item + 1 == props.type) pageMethod.drivingMap();
      },
      { immediate: true }
    );
    return {
      ...props,
      ...toRefs(pageData),
      ...pageMethod,
      ...compCall,
      ...comutedAll,
      changePublicAndPrivateFlag
    };
  }
};
</script>

<style scoped lang="less">
:deep(.fo-form .van-badge__wrapper) {
  color: #3eac8e;
}
:deep(.to-form .van-badge__wrapper) {
  color: #f85544;
}
:deep(.van-field__control) {
  color: #323233 !important;
  -webkit-text-fill-color: unset;
}
:deep(input.van-field__control::-webkit-input-placeholder) {
  color: #c8c9cc !important;
}
:deep(.van-cell__title) {
  color: #666666 !important;
}
</style>
